using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class CategoriaController : BaseController<CategoriaViewModel, Categoria, int>
    {
        public CategoriaController(ICategoriaService service)
            : base(service)
        {
        }

        public override ActionResult Index(int id = 0)
        {
            //- Creamos el modelo
            CategoriaViewModel model = new CategoriaViewModel();

            //- Buscamos la categoria
            if (id > 0) model.Entity = Service.Get(x => x.Id == id);

            return View(model);
        }

        public override ActionResult List(string filter, int page = 1)
        {
            CategoriaViewModel model = new CategoriaViewModel
            {
                Entities = this.Service.Find(x => filter == null || x.Nombre.Contains(filter))
                                                            .OrderBy(x => x.Nombre)
                                                            .Skip((page - 1) * PageSize)
                                                            .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = this.Service.Find(x => filter == null || x.Nombre.Contains(filter))
                                                            .Count()
                }
            };
            model.Filter = filter;     
            return View(model);
        }

        public override ActionResult Save(CategoriaViewModel model)
        {
            //- Guardamos o actualizamos
            if (model.Entity.Id > 0)
                ErrorList = this.Service.Update(model.Entity);
            else
                ErrorList = this.Service.Add(model.Entity);

            return ShowError(model, ErrorList);
        }
    }
}